package org.dsun.mvc.config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dsun.json.bean.JsonElement;
import org.dsun.json.bean.JsonObject;
import org.dsun.json.bean.JsonValue;
import org.dsun.json.bean.ValueList;
import org.dsun.mvc.entity.Action;
import org.dsun.mvc.entity.Result;
import org.dsun.reflect.Seter;

public class ConfigUtil {
	
	public static List<String> fetchIncludeFiles(JsonValue jv){
		List<String> list=new ArrayList<String>();
		if(jv.getValue() instanceof JsonObject){
			JsonObject jo=(JsonObject)jv.getValue();
			JsonElement jei=jo.getProperty("include");
			if(jei!=null){
			ValueList includeFile=(ValueList)jei.getValue().getValue();
				for(JsonValue j:includeFile){
					list.add(j.getValue().toString());
				}
			}
		}
		return list;
	}
	
	public static Map<String, String> fetchResultTypes(JsonValue jv){
		Map<String, String> map=new HashMap<String, String>();
		if(jv.getValue() instanceof JsonObject){
			JsonObject jo=(JsonObject)jv.getValue();
			JsonElement jer=jo.getProperty("resultType");
			if(jer!=null){
				JsonObject results=(JsonObject)jer.getValue().getValue();
				for(JsonElement je : results){
					map.put(je.getKey(), je.getValue().getValue().toString());
				}
			}
		}
		return map;
	}
	
	public static Map<String, Action> fetchActions(JsonValue jv,Map<String, String> resultTypes) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
		Map<String, Action> map=new HashMap<String, Action>();
		if(jv.getValue() instanceof JsonObject){
			JsonObject jo=(JsonObject)jv.getValue();
			JsonElement jea=jo.getProperty("actions");
			if(jea!=null){
				ValueList actions=(ValueList)jea.getValue().getValue();
				JsonObject ac;
				String url;
				String className;
				String method;
				Action action;
				JsonObject jsonResult;
				String type;
				Result result;
				String resultClass;
				for(JsonValue j : actions){
					ac=(JsonObject)j.getValue();
					url=ac.getProperty("url").getValue().getValue().toString();
					className=ac.getProperty("class").getValue().getValue().toString();
					method=ac.getProperty("method").getValue().getValue().toString();
					action=new Action();
					action.setActionClass(className);
					action.setActionMethod(method);
					JsonElement jer=ac.getProperty("result");
					if(jer!=null){
						jsonResult=(JsonObject)jer.getValue().getValue();
						type=jsonResult.getProperty("type").getValue().getValue().toString();
						resultClass=resultTypes.get(type);
						result=(Result)Class.forName(resultClass).newInstance();
						for(JsonElement je : jsonResult){
							if(!"type".equals(je.getKey())){
								Seter.invokeSeter(result, je.getKey(), je.getValue().getValue());
							}
						}
						action.setResult(result);
						map.put(url, action);
					}
				}
			}
		}
		return map;
	}
}
